package io.chance.receiverlei.db;

import lrq.common.MyLog;
import lrq.data.Model;
import org.apache.log4j.Logger;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * 数据池，为了提升性能，把接收到的数据缓存起来，达到一定数据量后再入库
 * @author gislin
 * 2016年3月2日
 */
public class DataPoolManager 
{
	private HashMap<String, List<DataPool>> dataPoolsMap = new HashMap<>();
	private static Logger log;
	
	private static DataPoolManager _instance;
	
	private DataPoolManager(){
		
	}
	
	public static DataPoolManager getInstance(){
		if(_instance == null){
			_instance = new DataPoolManager();
			log = MyLog.getLogger("DataPool");
		}
		return _instance;
	}

	public <T extends Model> void addModel(List<T> modelList) {
		
		if(modelList == null ||modelList.size() == 0){
			return;
		}
		
		String modelKey = modelList.get(0).getClass().getSimpleName();
		
		List<DataPool> dataPools = dataPoolsMap.get(modelKey);
		
		if(dataPools == null){
			dataPools = new ArrayList<>();
			for(int i=0;i<10;i++){
				dataPools.add(new DataPool(modelKey+"_"+i));
			}
			dataPoolsMap.put(modelKey, dataPools);
		}
		
		Date start = new Date();
		boolean done = false;
		
		while(!done){
			long timeDiff = ((new Date()).getTime() - start.getTime()) / 1000;
			
			if(timeDiff > 10){
				log.info(modelKey + ",插入超时,时间:"+timeDiff);
				done = true;
			}
			
			for(DataPool pool : dataPools){
				if(!pool.isExecuting()){
					pool.addModel(modelList);
					done = true;
					break;
				}
			}
		}
	}

	public HashMap<String, List<DataPool>> getDataPoolsMap() {
		return dataPoolsMap;
	}

	public void setDataPoolsMap(HashMap<String, List<DataPool>> dataPoolsMap) {
		this.dataPoolsMap = dataPoolsMap;
	}
	
}